<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="电表类型" prop="meterType">
        <el-select v-model="queryParams.meterType" placeholder="请选择电表类型" clearable size="small">
          <el-option
            v-for="dict in meterTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="识别结果" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择识别结果" clearable size="small">
          <el-option
            v-for="dict in stateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ai:reader:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ai:reader:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ai:reader:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ai:reader:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-download"
          size="mini"
          @click="handleAddAll"
          v-hasPermi="['ai:reader:addall']"
        > 批量上传
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-download"
          size="mini"
          @click="handleReadAll"
          v-hasPermi="['ai:reader:readALl']"
        > 批量识别
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-download"
          size="mini"
          @click="handleExportAllImg"
          v-hasPermi="['ai:reader:export']"
        >导出图片
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="readerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="电表类型" align="center" prop="meterType" :formatter="meterTypeFormat"/>
      <el-table-column label="识别结果" align="center" prop="state" :formatter="stateFormat"/>
      <el-table-column label="识别读数" align="center" prop="number"/>
      <el-table-column label="正确度数" align="center" prop="rightNumber"/>
      <el-table-column label="识别后图片" align="center" prop="readerImg">
        <template slot-scope="scope">
          <img :src="scope.row.readerImg" class="tableImage"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ai:reader:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ai:reader:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="uploadAll" width="600px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="图片" prop="readerImg">
          <el-upload
            list-type="picture"
            ref="uploadAllRef"
            :show-file-list="true"
            :http-request="uploadAllAdd"
            multiple
            action="http://192.168.1.237:7500/register_user"
            accept="image/*"
            :file-list="fileList"
            :auto-upload="false"

          >
            <el-button slot="trigger" type="primary">选取图片</el-button>
            <el-button type="primary" @click="uploadAllFile">全部上传</el-button>

          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加或修改电识别结果对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="原图" prop="img">
          <img :src="form.img" class="formImg"/>
          <el-input v-show="false" v-model="form.img"/>

        </el-form-item>

        <el-form-item label="识别图片" prop="readerImg">
          <img :src="form.readerImg" class="formImg"/>
          <el-input v-show="false" v-model="form.readerImg"/>
          <el-upload
            list-type="picture"
            :show-file-list="false"
            :data="fileImg"
            ref="uploadImg"
            action="http://192.168.1.237:7500/register_user"
            accept="image/*"
            :file-list="fileList"
            :on-success="uploadSuccess"
            :before-upload="beforeImageUpload"
          >
            <el-button type="primary" @click="showUpload">上  传</el-button>

          </el-upload>
        </el-form-item>

        <el-row>
          <el-col :span="16">
            <el-form-item label="文件名称">
              <el-input v-model="form.imgName" readonly="true"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="电表类型">
          <el-radio-group v-model="form.meterType">
            <el-radio-button v-for="tag in meterTypeOptions" :label="tag.dictValue">{{tag.dictLabel}}</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-row>
          <el-col :span="8">
            <el-form-item label="识别读数" prop="number">
              <el-input v-model="form.number" placeholder="请输入识别读数"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="正确度数" prop="rightNumber">
              <el-input v-model="form.rightNumber" placeholder="请输入正确度数"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer el-dialog--center ">
        <el-button type="primary" @click="submitForm(0)">识别正确</el-button>
        <el-button type="primary" @click="submitForm(3)">仅数字正确</el-button>
        <el-button type="primary" @click="submitForm(9)">识别错误</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
  import {listReader, getReader, delReader, addReader, updateReader, exportReader,exportImgReader} from "@/api/ai/reader";
  import ElButton from "../../../../node_modules/element-ui/packages/button/src/button";

  export default {
    components: {ElButton},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 电识别结果表格数据
        readerList: [],
        // 弹出层标题
        title: "11",
        // 是否显示弹出层
        open: false,
        uploadAll: false,
        uploadMeterImage: false,
        fileList: [],
        // 电表类型字典
        meterTypeOptions: [],
        // 识别结果字典
        stateOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          meterType: undefined,
          state: undefined,
        },
        fileImg: {},
        // 表单参数
        form: {},
        // 表单校验
        rules: {}
      };
    },
    created() {
      this.getList();
      this.getDicts("ai_meter_type").then(response => {
        this.meterTypeOptions = response.data;
      });
      this.getDicts("ai_meter_reader_state").then(response => {
        this.stateOptions = response.data;
      });
    },
    methods: {
      /** 查询电识别结果列表 */
      getList() {
        this.loading = true;
        listReader(this.queryParams).then(response => {
          this.readerList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 电表类型字典翻译
      meterTypeFormat(row, column) {
        return this.selectDictLabel(this.meterTypeOptions, row.meterType);
      },
      // 识别结果字典翻译
      stateFormat(row, column) {
        return this.selectDictLabel(this.stateOptions, row.state);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      showUpload(){
        this.$refs.uploadImg11.submit()
      },
      beforeImageUpload(file){

        var that = this
        this.blobToBase64(file).then(result => {
          console.log(result)
          that.form.img = result
        })

      },
      uploadSuccess(response, file, fileList){
        if (response && response.Status == 0) {
          this.form.readerImg = "data:image/jpeg;base64," + response.Pic
          let data = eval('(' + response.Data + ')');
          this.form.number = data.result
          this.form.imgName = this.form.imgName||file.name
          this.form.rightNumber = data.result
//        this.fileList.push({name:"1",src:"data:image/jpeg;base64,"+response.Pic})
          this.$refs.uploadImg.clearFiles()
        } else {
          this.$message.error('识别错误');
        }

      },
      // 表单重置
      reset() {
        this.form = {
          aiReaderId: undefined,
          meterType: undefined,
          state: undefined,
          number: undefined,
          rightNumber: undefined,
          img: undefined,
          img_name:undefined,
          readerImg: undefined,
          delFlag: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.aiReaderId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.open = true;
        this.reset();
        this.title = "批量上传电表图片";
      },
      /** 新增按钮操作 */
      handleAddAll() {
        this.uploadAll = true;
        this.reset();
        this.title = "批量上传电表图片";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const aiReaderId = row.aiReaderId || this.ids

        this.open = true;

        getReader(aiReaderId).then(response => {
          this.form = response.data;

          this.title = "修改电识别结果";
        });
      },
      /** 提交按钮 */
      submitForm: function (state) {
        this.form.state = state
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.aiReaderId != undefined) {
              updateReader(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.reset();
                  this.getList();
                  this.handleReadAll()
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              addReader(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  // this.open = false;
                  this.reset();
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const aiReaderIds = row.aiReaderId || this.ids;
        this.$confirm('是否确认删除电识别结果编号为"' + aiReaderIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delReader(aiReaderIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有电识别结果数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportReader(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function () {
        });
      },
      handleExportAllImg(){
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有电识别结果数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportImgReader(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function () {
        });
      },
      handleClick(tab, event) {
        console.log(tab, event);
      },
      blobToBase64(file) {
        return new Promise((resolve, reject) => {
          const fileReader = new FileReader();
          fileReader.onload = (e) => {
            resolve(e.target.result);
          };
          // readAsDataURL
          fileReader.readAsDataURL(file);
          fileReader.onerror = () => {
            reject(new Error('文件流异常'));
          };
        });
      },
      uploadAllFile(){
        this.$refs.uploadAllRef.submit();

      },
      uploadAllAdd(params){
        var that = this
        this.blobToBase64(params.file).then(res => {
          that.form.img = res;
          that.form.state = -1;
          that.form.imgName = params.file.name
          addReader(that.form).then(response => {
            if (response.code === 200) {
              that.msgSuccess("新增成功");
              // this.open = false;
              that.reset();
              that.getList();
              that.fileList = [];
            } else {
              that.msgError(response.msg);
            }
          })
        })

      },
      dataURLtoFile(dataurl, filename) {//将base64转换为文件
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type: mime});
      },
      handleReadAll(){
        var that = this
        var param = {
          state: -1,
          pageNum: 1,
          pageSize: 1
        }
        listReader(param).then(response => {
          if (!response.rows || response.rows.length == 0) {
            that.msgSuccess("无待识别数据");
            that.open = false;
            return;
          }
          that.handleUpdate(response.rows[0]);
          setTimeout(() => {
            var file = that.dataURLtoFile(response.rows[0].img);
            that.$refs.uploadImg.uploadFiles[0] = {status: "ready", raw: file}
            that.$refs.uploadImg.submit();
          }, 500);


        });


      }
    }
  };
</script>

<style lang="scss" scoped>
  .tableImage {
    width: 36px;
    height: 36px;
  }

  .formImg {
    height: 100px;
  }
</style>
